
const Service = require('egg').Service;

class ExeService extends Service {
    /**
     * 使用EXE的token来绑定本系统的用户，如果首次绑定，会先创建一个用户
     *
     * @param {*} ticket
     * @param {*} url
     * @return {*} 
     * @memberof ExeService
     */
    async doValid(ticket, url) {

        const ctx = this.ctx;
        return new Promise(async (resolve, reject) => {
            const result = await ctx.curl(`${url}/api/Ticket/V2?id=${ticket}`, {
                dataType: 'json',
                timeout: 5000,
                method: 'GET',
                headers: {
                    "Accept-Language": 'zh-CN',
                },
                contentType: "application/json"
            });
            if (result && result.status === 200) {
                const { data } = result
                if (data && data.success && data.data.success) {
                    const userData = data.data
                    const openId = `${userData.tenantId}_${userData.userCode}_${userData.userId}`

                    let userInfo = {
                        name: userData.name,
                        sex: userData.sex,
                        openId,
                        userType: 1
                    }

                    const user = await ctx.model.User.findOne({ openId });
                    if (user) {
                        resolve(user);
                    } else {
                        ctx.model.Role.findOne({ name: ctx.app.constant.DEFAULT_ROLE }).lean().exec((err, role) => {
                            if (role) {
                                userInfo.role = role._id;
                            }
                            ctx.model.User({
                                openId: openId,
                                ...userInfo
                            }).save((err, data) => {
                                if (err) {
                                    reject(err);
                                    return
                                }
                                resolve({ _id: data._id, ...data, role })
                            });
                        });
                    }

                } else {
                    reject(new Error('验证用户失败，请重试！'))
                }
            } else {
                reject(new Error('验证用户失败，请重试！'))
            }
        })
    }
    async loginValid(ticket) {
        const ctx = this.ctx;
        const url = ctx.app.constant.EXE.LOGIN_URL
        return this.doValid(ticket, url)
    }
    async loginValidTest(ticket) {
        const ctx = this.ctx;
        const url = ctx.app.constant.EXE.LOGIN_URL_TEST
        return this.doValid(ticket, url)
    }
}

module.exports = ExeService;
